package top.bingoz.wanandroid.ui.widget

import android.content.Context
import android.support.annotation.ColorRes
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import com.alibaba.android.vlayout.DelegateAdapter
import com.alibaba.android.vlayout.VirtualLayoutManager
import com.scwang.smartrefresh.layout.api.RefreshLayout
import kotlinx.android.synthetic.main.my_recycler_view.view.*
import top.bingoz.wanandroid.R


/**
 * Created by 唐小妹 on 2018/6/12.
 */
class MyRecyclerView : RelativeLayout {
    private lateinit var delegateAdapter: DelegateAdapter
    private lateinit var layoutManager: VirtualLayoutManager
    private var adapterNum = 0
    private var adapters: ArrayList<DelegateAdapter.Adapter<*>> = ArrayList()

    constructor(context: Context) : super(context) {
        initView(context)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        initView(context)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initView(context)
    }

    private fun initView(context: Context) {
        LayoutInflater.from(context).inflate(R.layout.my_recycler_view, this)

//        refreshLayout.isEnableAutoLoadMore = true
//        refreshLayout.autoLoadMore()
//        refreshLayout.isEnablePureScrollMode = true//是否启用纯滚动模式
//        refreshLayout.setEnableFooterFollowWhenLoadFinished(true)//是否在全部加载结束之后Footer跟随内容1.0.4

        //加载中动画
//        (loadImage.drawable as AnimationDrawable).start()

//        ((SimpleItemAnimator)rvList.getItemAnimator()).setSupportsChangeAnimations(false)
//        (rvList.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
//        rvList.itemAnimator.changeDuration = 0

        layoutManager = object : VirtualLayoutManager(context) {
            override fun getExtraLayoutSpace(state: RecyclerView.State?): Int {
                return 300
            }
        }
        rvList.layoutManager = layoutManager
        delegateAdapter = DelegateAdapter(layoutManager, false)
        rvList.adapter = delegateAdapter

        //设置回收复用池大小，（如果一屏内相同类型的 View 个数比较多，需要设置一个合适的大小，防止来回滚动时重新创建 View）
        val viewPool = RecyclerView.RecycledViewPool()
        rvList.recycledViewPool = viewPool
        viewPool.setMaxRecycledViews(0, 40)

        //回到顶部按钮
        ivBackTop.setOnClickListener {
            refreshLayout.finishLoadMore(0)
            rvList.scrollToPosition(0)
        }
    }

    fun addOnScrollListener(listener: RecyclerView.OnScrollListener) {
        rvList.addOnScrollListener(listener)
    }

    fun showBackTopButton(show: Boolean) {
        if (show)
            ivBackTop.visibility = View.VISIBLE
        else
            ivBackTop.visibility = View.GONE
    }

    fun getLayoutManager(): VirtualLayoutManager {
        return layoutManager
    }


    //展示顶部按钮
    fun addBackTopButton() {
        //recycleView滚动监听 展示||隐藏 回到顶部按钮
        rvList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
//                val currPosition = layoutManager.getPosition(rvList.getChildAt(adapterNum))
                val currPosition = layoutManager.findFirstVisibleItemPosition()
                //当position大于5，显示返回顶部按钮
                if (currPosition > 10) {
                    ivBackTop.visibility = View.VISIBLE
                } else {
                    ivBackTop.visibility = View.GONE
                }
            }
        })
    }

    //添加适配器
    fun addAdapter(adapter: DelegateAdapter.Adapter<*>) {
        delegateAdapter.addAdapter(adapter)
        adapterNum++
        adapters.add(adapter)
    }

    fun getAdapterSize(): Int {
        return adapterNum
    }

    //请求是否完成
    fun loadFinish(isRefresh: Boolean = true) {
        if (loadView?.visibility == View.VISIBLE)
            loadView?.visibility = View.GONE
        if (refreshLayout != null && loadView.visibility == View.GONE)
            if (isRefresh)
                refreshLayout.finishRefresh()
            else
                refreshLayout.finishLoadMore()
    }

    //刷新监听
    fun setOnRefreshListener(backCall: (refreshLayout: RefreshLayout) -> Unit) {
        refreshLayout.setOnRefreshListener { layout ->
            layout.setNoMoreData(false)
            backCall(layout)
        }
    }

    //加载更多监听
    fun setOnLoadMoreListener(backCall: (refreshLayout: RefreshLayout) -> Unit) {
        refreshLayout.setOnLoadMoreListener { layout ->
            backCall(layout)
        }
    }

    //滚动到指定item
    fun scrollToPosition(position: Int = 0, offset: Int = 0) {
        rvList ?: return
        rvList.stopScroll()
        layoutManager.scrollToPositionWithOffset(position, offset)
        refreshLayout.setEnableNestedScroll(true)
    }

    //禁止刷新
    fun setUnRefresh() {
        refreshLayout.isEnableRefresh = false
        refreshLayout.setEnableOverScrollDrag(false)
//        refreshLayout.setEnableHeaderTranslationContent(false)
    }

    //禁止加载更多
    fun setUnLoadMore(isNoMore: Boolean = false) {
        if (isNoMore) {//没有更多数据  并且展示没有更多数据的状态
            refreshLayout.finishLoadMoreWithNoMoreData()
            refreshLayout.setNoMoreData(true)
            refreshLayout.setEnableFooterFollowWhenLoadFinished(true)
        } else {//没有更多数据 并且不能上拉
            refreshLayout.isEnableLoadMore = false
            refreshLayout.setEnableOverScrollDrag(false)
        }

    }

    fun showLoadView(show: Boolean = true) {
        if (show)
            loadView.visibility = View.VISIBLE
        else
            loadView.visibility = View.GONE
    }

    /**
     * 重置加载更多状态
     */
    fun resetLoadMore(refresh: Boolean) {
        refreshLayout.isEnableLoadMore = refresh
        refreshLayout.setEnableOverScrollDrag(refresh)
        refreshLayout.setEnableFooterTranslationContent(refresh)
    }

    /**
     * 重置刷新状态
     */
    fun resetRefresh(state: Boolean) {
        refreshLayout?.isEnableRefresh = state
        refreshLayout?.setEnableHeaderTranslationContent(state)
    }

    fun setRefreshLayoutBackground(@ColorRes color: Int) {
        refreshLayout.setBackgroundResource(color)
    }

    fun deleteAdapter() {
        delegateAdapter.clear()
    }
}